var baseURL = "/dqms/";
var undefinedText = "-"; //列表字段值为空展示内容

var contextPath = document.location.pathname;
var index =contextPath.substr(1).indexOf("/"); //这个地方可能有问题，要根据具体项目适当修改
baseURL = contextPath.substr(0,index+2);

//登录token
var token = sessionStorage.getItem("token");

//暂时先屏蔽掉
//if(token == null){
if(location.href.indexOf("sec=") != -1){

  var sec = location.href.split("sec=")[1];
  $.ajax({
    type: "POST",
    dataType: "json",
    async:false,
    url: "login?sec="+sec,
    success: function (jsonData) {
      if (jsonData.code == 200) {//登录成功
        console.info("sec:"+sec);
        sessionStorage.setItem("token", jsonData.token);
        localStorage.setItem("userName", jsonData.userName);
        localStorage.setItem("username", jsonData.username);
        localStorage.setItem("jgbm", jsonData.jgbm);
        localStorage.setItem("jgmc", jsonData.jgmc);
        localStorage.setItem("zclsh",jsonData.zclsh);
        localStorage.setItem("showDate",jsonData.showDate);
        //location.href = 'index.html?sec='+sec;
        var addrStr = location.href;
        addrStr = addrStr.substring(0,addrStr.indexOf('?sec'));
        location.href = addrStr;
      }
    }
  });
  //}else{
  // location.href = baseURL + 'login.html';
  // }

}

if (location.href.indexOf("ticket=") != -1) {
  var ticket = location.href.split("ticket=")[1];
  $.ajax({
    type: "POST",
    dataType: "json",
    async: false,
    url: "login?ticket=" + encodeURI(ticket),
    success: function (jsonData) {
      if (jsonData.code == 200) {//登录成功
        console.info("ticket:" + ticket);
        sessionStorage.setItem("token", jsonData.token);
        localStorage.setItem("userName", jsonData.userName);
        location.href = location.href.split("?ticket=")[0].split("dqms/")[1];
      } else {
          localStorage.setItem("token", "");
      }
    }
  });
}

//jquery全局配置
$.ajaxSetup({
  dataType: "json",
  cache: false,
  headers: {
    "token": token
  },
  complete: function(xhr) {
    //token过期，则跳转到登录页面
    if(xhr.responseJSON !=undefined && xhr.responseJSON.code == 401){
      if(location.href.indexOf("sec=") != -1){
        var sec = location.href.split("sec=")[1];
        $.ajax({
          type: "POST",
          dataType: "json",
          async:false,
          url: "login?sec="+sec,
          success: function (jsonData) {
            if (jsonData.code == 200) {//登录成功
              console.info("sec:"+new Date());
              sessionStorage.setItem("token", jsonData.token);
              localStorage.setItem("userName", jsonData.userName);
              var addrStr = location.href;
              addrStr = addrStr.substring(0,addrStr.indexOf('?sec'));
              location.href = addrStr;
            }
          }
        });
      }else{
        top.location.href = baseURL + 'login.html';
      }
    }
  }
});



/**
 * 通用类
 */
var Common = {

  /**
   * ajax请求封装
   * @param url 请求路径：相对路径
   * @param paramObj 请求参数列表O
   * @param succCallBackFunction 成功的回调函数：异步请求下，才会调用
   * @param isAsync  是否异步，默认为true，异步； false为同步
   * @param type    请求方法名称，post get put delete（TEST）
   * @param dataType  json格式
   */
  ajaxHandler: function (url, paramObj, isAsync, type) {
    //如果上层不传入具体的值，则默认为异步，(默认: true) 默认设置下，所有请求均为异步请求
    if (isAsync == null || isAsync == "") {
      isAsync = true;
    }

    if (type == null || isAsync == "") {

    }

    $.ajax({
      url: url,
      type: type,
      dataType: "json",
      success: function (jsonData) {

      }
    });
  },

  /**
   * 请求参数获取
   */
  GetRequest: function() {
    var url = location.search; //获取url中"?"符后的字串
    var theRequest = new Object();
    if (url.indexOf("?") != -1) {
      var str = url.substr(1);
      str = str.split("&");
      for(var i = 0; i < str.length; i ++) {
        theRequest[str[i].split("=")[0]]=unescape(str[i].split("=")[1]);
      }
    }
    return theRequest;
  },

  GetRequestWithChinese: function() {
    var url = location.search; //获取url中"?"符后的字串
    var theRequest = new Object();
    if (url.indexOf("?") != -1) {
      var str = url.substr(1);
      str = str.split("&");
      for(var i = 0; i < str.length; i ++) {
        theRequest[str[i].split("=")[0]]=decodeURIComponent(str[i].split("=")[1]);
      }
    }
    return theRequest;
  },

  /**
   * JS正则表达式验证是否为11位有效手机号码
   * @returns {boolean}
   */
  isPoneAvailable:function (tele) {
    var myreg=/^[1][2,3,4,5,6,7,8,9][0-9]{9}$/;
    if (tele !=""&& tele !=undefined  && !myreg.test(tele)) {
      return false;
    } else {
      return true;
    }
  },

  /**
   * 获取 数据源值域目录数椐
   * @param zydm 值域代码
   * @param selectId 下拉框ID
   * demo   Common.GetSjyzy("CV02.01.101","testSelect");
   * w_jx 防止出现空白一行 显示 --请选择--
   */
  GetSjyzy: function(zydm,selectId) {

    if(zydm!=null&&zydm!="")
    {
      $.ajax({
        type: "GET",
        contentType: 'application/x-www-form-urlencoded',
        async:false,
        dataType: "json",
        url: "commonapi/zyinfo",
        data:
            {
              zydm:zydm
            },
        success: function (jsonData) {
          if (jsonData.code == 200) {   //查询成功
            var list = jsonData.sjyzymlEntity;
            var optionhtml = '<option  value="" >--请选择--</option>';
            if(list.length >0){
              for (var i = 0; i < list.length; i++) {
                var data = list[i];
                optionhtml +='<option  value= "' + data.zdm +'" >' + data.zmc + '</option>';
              }
            }
            $('#'+selectId).append(optionhtml);

          }
        }
      });

    }

  },

  /***
   * 获取管理年度
   */
  initGlnd:function (glndId) {
    var myDate = new Date();
    var dqnd = myDate.getFullYear().toString();
    var list = new Array()
    list[0] = dqnd;
    list[1] = dqnd-1;
    list[2] = dqnd-2;
    list[3] = dqnd-3;
    list[4] = dqnd-4;

    var optionhtml = '';
    if(list.length >0){
      for (var i = 0; i < list.length; i++) {
        var data = list[i];
        optionhtml +='<option value="'+data+'">' + data + '</option>';
      }
    }
    $('#'+glndId).append(optionhtml);
  },

  /**
   * 功能按钮-权限过滤
   *
   */
  qxGnan: function() {

    if(mcode !=undefined && mcode!=null)
    {
      $.ajax({
        type: "GET",
        contentType: 'application/json',
        dataType: "json",
        url: baseURL+"commonapi/getCzryqx/"+mcode,
        success: function (jsonData) {
          if (jsonData.code == 200) {
            var noQxlist = jsonData.noQxlist;
            var reg = new RegExp(":","g");
            if(noQxlist.length >0) {
              $.each(noQxlist, function (index, entity) {
                var temp = entity.gndm.replace(reg,"");
                if($("."+temp).length>0)
                {
                  $("."+temp).removeAttr('href');//去掉a标签中的href属
                  $("."+temp).removeAttr('onclick');//去掉a标签中的onclick事件
                  $("."+temp).css("opacity","0.2");
                }
              })
            }

          }
        }
      });
    }

  },

  /**
   * 身份证校验
   * @param zjhm
   * @returns {boolean}
   */
  jySfzh:function(zjhm){
    var code = zjhm;
    // var city={11:"北京",12:"天津",13:"河北",14:"山西",15:"内蒙古",21:"辽宁",22:"吉林",23:"黑龙江 ",31:"上海",32:"江苏",33:"浙江",34:"安徽",35:"福建",36:"江西",37:"山东",41:"河南",42:"湖北 ",43:"湖南",44:"广东",45:"广西",46:"海南",50:"重庆",51:"四川",52:"贵州",53:"云南",54:"西藏 ",61:"陕西",62:"甘肃",63:"青海",64:"宁夏",65:"新疆",71:"台湾",81:"香港",82:"澳门",91:"国外 "};
    var tip = "";
    var pass= true;

    if(!code){
      tip = "身份证号不能为空";
      pass = false;
    }else if(/**!code ||**/ !/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i.test(code)){
      tip = "身份证号格式错误";
      pass = false;
    }

    /* else if(!city[code.substr(0,2)]){
         tip = "地址编码错误";
         pass = false;
     }
     else{
         //18位身份证需要验证最后一位校验位
         if(code.length == 18){
             code = code.split('');
             //∑(ai×Wi)(mod 11)
             //加权因子
             var factor = [ 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 ];
             //校验位
             var parity = [ 1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2 ];
             var sum = 0;
             var ai = 0;
             var wi = 0;
             for (var i = 0; i < 17; i++)
             {
                 ai = code[i];
                 wi = factor[i];
                 sum += ai * wi;
             }
             var last = parity[sum % 11];
             if(parity[sum % 11] != code[17]){
                 tip = "校验位错误";
                 pass =false;
             }
         }
     }*/
    if(!pass) {
      LayerWn.showFailAlert(tip,0);
      //$("#"+id).focus();
    }//alert(tip);
    return pass;
  },

  /**
   * 根据身份证号码计算出生日期
   * @param zjhm
   * @returns {string} YYYYMMDD格式
   */
  jsCsrq:function(zjhm){
    var csrq = "";
    var n = "";
    var y = "";
    var r = "";
    if(zjhm.length == 15){
      n = "19"+zjhm.substring(6,8);
      y = zjhm.substring(8,10);
      r = zjhm.substring(10,12);
    }else if(zjhm.length == 18){
      n = zjhm.substring(6,10);
      y = zjhm.substring(10,12);
      r = zjhm.substring(12,14);
    }
    csrq = n+""+y+""+r;
    return csrq;
  },
  /**
   * 根据身份证号码计算出生日期
   * @param zjhm
   * @returns {string} YYYY-MM-DD格式
   */
  jsCsrqYMD:function(zjhm){
    var csrq = "";
    var n = "";
    var y = "";
    var r = "";
    if(zjhm.length == 15){
      n = "19"+zjhm.substring(6,8);
      y = zjhm.substring(8,10);
      r = zjhm.substring(10,12);
    }else if(zjhm.length == 18){
      n = zjhm.substring(6,10);
      y = zjhm.substring(10,12);
      r = zjhm.substring(12,14);
    }
    csrq = n+"-"+y+"-"+r;
    return csrq;
  },

  /**
   * 根据身份证号码计算性别
   * @param zjhm
   */
  jsXb:function(zjhm){
    var xbdm = "";
    if(zjhm.length == 15) {
      if (parseInt(zjhm.substring(14, 15)) % 2 == 1)
        xbdm = "1";
      else
        xbdm = "2";
    }else if(zjhm.length == 18){
      if(parseInt(zjhm.substring(16,17))%2 == 1)
        xbdm = "1"
      else
        xbdm = "2";
    }
    return xbdm;
  },

  jyNumberic:function(id,length,precLen,name){
    var value = $("#"+id).val();
    //var message = "数字型"+name+"输入错误。长度应为:"+length;
    //eval("var reg = ^(?!^0*(\.0{1,2})?$)^\d{1,"+length+"}(\.\d{1,"+precLen+"})?$/;");
    //eval("var reg1 = /^(?!^0*(\\.0{1,2})?$)^\\d{1,13}(\\.\\d{1,2})?$/;");
    if(value!=null && value != "" && value != 0){
      if(precLen && precLen != 0){
        eval("var reg = /^(?!^0*(\\.0{1,2})?$)^\\d{1,"+(length-precLen)+"}(\\.\\d{1,"+precLen+"})?$/;");
        //message += ",精度应为:"+precLen;
      }else{
        eval("var reg = /^(?!^0*(\\.0{1,2})?$)^\\d{1,"+length+"}$/;");
      }
      return reg.test(value);
    }
    return true;

    //LayerWn.showFailAlert(message,0);
    //return false;
    //}
  },

  /**
   * 单个电话号码的校验 非必填项
   * @param telnumber
   */
  telValidate:function (telnumber) {
    if(null == telnumber || "" == telnumber || undefined == telnumber){
      return true;
    }
    if(/^(\(\d{3,4}\)|\d{3,4}-|\s)?\d{7,14}$/.test(telnumber)){
      return true;
    }else{
      return false;
    }
  },

  /**
   * 多个电话用,号分隔 非必填项
   * @param telnumbers
   * @returns {boolean}
   */
  telsValidate:function (telnumbers) {
    var telsArray= new Array(); //定义一数组
    if(null == telnumbers || "" == telnumbers || undefined == telnumbers){
      return true;
    }
    if(telnumbers.indexOf(',') != -1){
      telsArray = telnumbers.split(","); //字符分割
    }
    if(telnumbers.search('，') != -1){
      telsArray = telnumbers.split("，"); //字符分割
    }
    if(telsArray.length>0){
      for(var i=0;i<telsArray.length ;i++ ){
        if(!this.telValidate(telsArray[i])){
          return false;
        }
      }
    }else{
      return this.telValidate(telnumbers);
    }
    return true;
  },
  /**
   *数据校验不能为空
   * @param domid
   * @param msg
   */
  validate:function (domid,msg) {
    var val = $.trim($("#"+domid).val());
    if ('' == val || undefined == val) {
      LayerWn.showAlert(msg);
      return true;
    }
    return false;
  }
};


//form表单序列化
(function($){
  $.fn.serializeJson=function(){
    var serializeObj={};
    var array=this.serializeArray();
    var str=this.serialize();

    $(array).each(function(){
      if(serializeObj[this.name]){
        if($.isArray(serializeObj[this.name])){
          serializeObj[this.name].push(this.value);
        }else{
          serializeObj[this.name]=[serializeObj[this.name],this.value];
        }
      }else{
        serializeObj[this.name]=this.value;
      }
    });

    var $radio = $('input[type=radio],input[type=checkbox]',this);
    $.each($radio,function(){
      if(!serializeObj.hasOwnProperty(this.name)){
        serializeObj[this.name] = '0';
      }
    });

    return serializeObj;
  };
})(jQuery);


//全局参数，三级菜单编码
var mcode = null;
var noAnQxlist = [];
//按钮权限验证
$(function () {
  if("third"==Common.GetRequest().cdType){
    mcode =  Common.GetRequest().mcode;
  }
  if(mcode !=undefined && mcode!=null)
  {
    $.ajax({
      type: "GET",
      contentType: 'application/json',
      dataType: "json",
      url: baseURL+"commonapi/getCzryqx/"+mcode,
      success: function (jsonData) {
        if (jsonData.code == 200) {
          var noQxlist = jsonData.noQxlist;
          noAnQxlist = noQxlist;
          var reg = new RegExp(":","g");
          if(noQxlist.length >0) {
            $.each(noQxlist, function (index, entity) {
              if(entity.url!=null)
              {
                var temp = entity.url.replace(reg,"");
                if($("#"+temp).length>0)
                {
                  $("#"+temp).attr('disabled',true);
                }
              }

            })
          }

        }
      }
    });
  }
});

function paramsMatter(value,row,index) {
  var span=document.createElement('span');
  span.setAttribute('title',value);
  span.innerHTML = value;
  return span.outerHTML;
}

function formatTableUnit(value, row, index) {
  return {
    css: {
      "white-space": 'nowrap',
      "text-overflow": 'ellipsis',
      "overflow": 'hidden'
    }
  }
}

/**
 * 初始化数字滚动效果
 */
function initCounterUp(){
  if (!$().counterUp) {
    return;
  }
  $("[data-counter='counterup']").counterUp({
    delay: 10,
    time: 1000
  });
}

/**
 * 格式化毫秒，超过1000自动转换为秒
 */
function formatMilliSecond(time){
  if(Number(time) <= 1000){
    return time+"ms";
  }else if(Number(time) < 0){
    return "0ms";
  }else{
    return (Number(time)/1000).toFixed(2)+"s";
  }
}
function menuClink(href,index,name) {
  var o = href,
      m = index,
      l = name,
      k = true;
  if (o == undefined || $.trim(o).length == 0) {
    return false
  }
  var targetMenu = $(window.parent.document).find(".J_menuTab").filter(":contains('" + l + "')");
  if(targetMenu.length ==1){
      targetMenu.addClass("active").siblings().removeClass("active");
      var n = '<iframe class="J_iframe" name="iframe' + m + '" width="100%" height="100%" src="' + o + '" frameborder="0" data-id="' + o + '" seamless></iframe>';
      $(window.parent.document).find(".J_mainContent").find("iframe.J_iframe").hide().parents(".J_mainContent").append(n);
      ($(".J_menuTab.active"));
      return false;
  }

  $(".J_menuTab").each(function () {
    if ($(this).data("id") == o) {
      if (!$(this).hasClass("active")) {
        $(this).addClass("active").siblings(".J_menuTab").removeClass("active");
        g(this);
        $(".J_mainContent .J_iframe").each(function () {
          if ($(this).data("id") == o) {
            $(this).show().siblings(".J_iframe").hide();
            return false
          }
        })
      }
      k = false;
      return false
    }
  });
  if (k) {
    var p = '<a href="javascript:;" class="active J_menuTab" data-id="' + o + '">' + l + ' <i class="fa fa-times-circle"></i></a>';
    $(window.parent.document).find(".J_menuTab").removeClass("active");
    var n = '<iframe class="J_iframe" name="iframe' + m + '" width="100%" height="100%" src="' + o + '" frameborder="0" data-id="' + o + '" seamless></iframe>';
    $(window.parent.document).find(".J_mainContent").find("iframe.J_iframe").hide().parents(".J_mainContent").append(n);
    $(window.parent.document).find(".J_menuTabs .page-tabs-content").append(p);
    ($(".J_menuTab.active"));
  }
  return false
}

/**
 * 构建请求参数，请求url需手动加上？符号
 * @param paramMap {"a":1, "b":2}
 * @returns {string} key1=value1&key2=value2&...&keyN=valueN
 */
function buildRequestParams(paramMap) {

    if (paramMap === null || paramMap === undefined || Object.keys(paramMap).length === 0) {
        return "";
    } else {
        var paramString = "";
        for (key in paramMap) {
            paramString += (key + "=" + paramMap[key] + "&");
        }
        return paramString.substring(0, paramString.length - 1);
    }
}